<template>
  <div class="ditchBox pageWrapperForm">
    <Loading :loading="loading">
      <Form ref="formData" :label-width="160" :model="formData" inline :rules="ruleFormData">
        <Card :bordered="true">
          <p slot="title">商户基本信息</p>
          <FormItem prop="organizationCode" label="机构名称：" style="width:40%">
            <Select v-model="formData.organizationCode" :label-in-value="true" placeholder="请选择"
                    @on-change="blandleOrganization" clearable filterable>
              <Option v-for="(item, index) in oNameSelect" :value="item.value" :key="index + item.value">{{item.label}}</Option>
            </Select>
          </FormItem>
          <FormItem label="商户编码：" style="width:40%">
            <Input type="text" v-model="formData.merchantCode" placeholder="请填写,字数不超过32" :maxlength="maxlength"
                   clearable/>
          </FormItem>
          <FormItem prop="merchantName" label="商户名称：" style="width:40%">
            <Input type="text" v-model="formData.merchantName" placeholder="请填写,字数不超过25" maxlength='25'
                   clearable/>
          </FormItem>
          <FormItem prop="openingBank" label="开户行：" style="width:40%">
            <Input type="text" v-model="formData.openingBank" placeholder="请填写,字数不超过32" :maxlength="maxlength"
                   clearable/>
          </FormItem>
          <FormItem prop="accountName" label="开户名：" style="width:40%">
            <Input type="text" v-model="formData.accountName" placeholder="请填写,字数不超过32" :maxlength="maxlength"
                   clearable/>
          </FormItem>
          <FormItem prop="bankCode" label="开户行行号：" style="width:40%">
            <Input type="text" v-model="formData.bankCode" placeholder="请填写,字数不超过12" :maxlength="maxlength"
                   clearable/>
          </FormItem>
          <FormItem prop="accountType" label="结算账户类型：" style="width:40%">
            <Select v-model="formData.accountType" placeholder="请选择" clearable>
              <Option v-for="(item, index) in selectAccount" :value="item.key" :key="index">{{ item.value }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="accountNo" label="账号：" style="width:40%">
            <Input type="text" v-model="formData.accountNo" placeholder="请填写,字数不超过32" :maxlength="maxlength"
                   clearable/>
          </FormItem>
          <FormItem prop="city" label="城市" style="width:40%">
            <!-- <Select v-model="formData.cityCode" placeholder="请选择" clearable>
              <Option v-for="(item, index) in cityList" :key="item + index" :value="item.id">{{ item.name }}</Option>
            </Select> -->
            <Cascader :data="cityList" v-model="formData.city" :load-data="cityLoadData"
                      @on-change="getCityName"></Cascader>
          </FormItem>
          <FormItem prop="revenueType" label="收入规则" style="width:40%">
            <!-- <Select v-model="formData.cityCode" placeholder="请选择" clearable>
              <Option v-for="(item, index) in cityList" :key="item + index" :value="item.id">{{ item.name }}</Option>
            </Select> -->
            <Select v-model="formData.revenueType" placeholder="请选择" clearable>
              <Option v-for="(item, index) in selectRevenueTypeList" :value="item.value" :key="index + item.value">
                {{ item.label }}
              </Option>
            </Select>
          </FormItem>
          <br/>
          <FormItem prop="channelListType" label="渠道选择：" style="width:40%">
            <Select v-model="formData.channelListType" multiple placeholder="请选择" :label-in-value='true'
                    @on-change="getDitch" clearable>
              <Option v-for="(item, index) in selectChannel" :key="item + index" :value="item.key">{{ item.value }}
              </Option>
            </Select>
          </FormItem>
          <FormItem label="平台应收比例:" v-if="formData.revenueType ==='FIXED_SCALE'" style="width:40%">
            <Input type="number" v-model="formData.platformRevenueCcale" :autosize="true"
                   placeholder="平台应收比例" clearable>
              <span slot="append">%</span>
            </Input>

          </FormItem>
          <FormItem label="平台应收金额:" v-else-if="formData.revenueType ==='FIXED_AMOUNT'" style="width:40%">
            <Input type="number" v-model="formData.platformRevenueAmount" :autosize="true"
                   placeholder="平台应收金额" clearable>
              <span slot="append">分</span>
            </Input>
          </FormItem>
          <br/>
          <FormItem prop="scene" label="场景选择：" style="width:40%">
            <Select v-model="formData.scene" multiple placeholder="请选择" :label-in-value='true' clearable>
              <Option v-for="(item, index) in selectScenario" :key="item + index" :value="item.key">{{ item.value }}
              </Option>
            </Select>
          </FormItem>

          <FormItem prop="settlementType" label="结算类型：" style="width:40%">
            <Select v-model="formData.settlementType" placeholder="请选择" :label-in-value='true' clearable>
              <Option v-for="(item, index) in settlementTypes" :key="item + index" :value="item.key">{{ item.value }}
              </Option>
            </Select>
          </FormItem>
          <!-- <FormItem prop="beginTime" label="合同起始时间：" style="width:40%">
            <DatePicker type="daterange" v-model="formData.beginTime" format="yyyy-MM-dd" placeholder="请选择" @on-change="setDateRange" clearable></DatePicker>
          </FormItem> -->
          <FormItem label="备注:" style="width:40%">
            <Input type="textarea" v-model="formData.remark" show-word-limit maxlength="200" :autosize="true"
                   placeholder="请填写" clearable/>
          </FormItem>
        </Card>
        <!-- 动态添加 渠道 -->
        <Card :bordered="true" v-if="formData.channelList && formData.channelList.length>0" style="margin-top: 15px">
          <div v-for="(item, index) in formData.channelList" :key="item + index">
            <Divider style="color: #2d8cf0;text-align: center" dashed orientation="left">{{ item.paymentChannelName }}
              <span style="font-size: 13px;padding-left: 10px;color: rgb(81, 90, 110)">设为默认支付渠道:</span>
              <iSwitch
                true-color="#13ce66"
                false-color="#ff4949"
                true-value="1"
                false-value="0"
                v-model="formData.channelList[index].used">
                <span slot="open">是</span>
                <span slot="close">否</span>
              </iSwitch>
            </Divider>
            <!--          <FormItem :prop="'channelList.' + index + '.subMchId'" :rules="[{ required: true, validator: validateTageCount, trigger: 'blur', index: index }]" label="支付渠道子商户号：" style="width:40%">-->
            <FormItem label="支付渠道子商户号：" style="width:40%">
              <Input type="text" v-model.trim="formData.channelList[index].subMchId" placeholder="请填写,字数不超过32"
                     clearable/>
            </FormItem>
            <FormItem label="业务侧商户编码：" style="width:40%">
              <Input type="text" v-model.trim="formData.channelList[index].merchantCodeBusiness"
                     placeholder="请填写,字数不超过64" maxlength="64" clearable/>
            </FormItem>
            <FormItem label="收单机构商户号：" style="width:40%">
              <Input type="text" v-model.trim="formData.channelList[index].merchantCodeAcquirer"
                     placeholder="请填写,字数不超过32" :maxlength="maxlength" clearable/>
            </FormItem>
            <FormItem :prop="'channelList.' + index + '.subAppid'"
                      :rules="[{ required: true, message: '请填写', trigger: 'blur', index: index }]"
                      label="渠道进件号：" style="width:40%">
              <Input type="text" v-model.trim="formData.channelList[index].subAppid" placeholder="请填写,字数不超过32"
                     :maxlength="maxlength" clearable/>
            </FormItem>
            <FormItem :prop="'channelList.' + index + '.merchantSlottingFees'"
                      :rules="[{ required: true, validator: validateTage, trigger: 'blur', index: index }]"
                      label="平台服务费：" style="width:40%">
              <Input type="text" v-model="formData.channelList[index].merchantSlottingFees"
                     placeholder="请填写" clearable>
                <span slot="append">%</span>
              </Input>
            </FormItem>
            <FormItem :prop="'channelList.' + index + '.platformSlottingFees'"
                      :rules="[{ required: true, validator: validateTageCheak, trigger: 'blur', index: index}]"
                      label="平台通道费：" style="width:40%">
              <Input type="text" v-model="formData.channelList[index].platformSlottingFees"
                     placeholder="请填写" clearable>
                <span slot="append">%</span>
              </Input>
            </FormItem>
            <FormItem :prop="'channelList.' + index + '.enterpriseCode'"
                      :rules="[{ required: true, message: '请填写', trigger: 'blur', index: index }]"
                      label="企业用户号：" style="width:40%" v-if="item.paymentChannelCode === 'ums'">
              <Input type="text" v-model="formData.channelList[index].enterpriseCode" placeholder="请填写"
                     :maxlength="maxlength" clearable/>
            </FormItem>
          </div>
        </Card>
        <div style="text-align: center; margin-top: 20px">
          <Button style="margin-right: 10px" @click="handleSubmitCancel('formData')">取消</Button>
          <Button type="primary" @click="handleSubmit('formData')">确定</Button>
        </div>
      </Form>
    </Loading>
  </div>
</template>
<script>
import {namespace} from '../module/commercial.js';
import Loading from '@/components/Loading';
import RemoteSelect from '@/components/RemoteSelect';
import RemoteTableSelect from '@/components/RemoteTableSelect';
import SearchBar from '@/components/SearchBar';
import Uuid from 'uuid';
import Authc from '@/components/Authc';
import {Modal} from "view-design";

export default {
  components: {
    Loading,
    RemoteSelect,
    RemoteTableSelect,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    Authc
  },
  props: ['id'],
  beforeMount: async function () {
    // let id = this.$route.params.id;
    // let response = await this.$store.dispatch(`${namespace}/getDetail`, {
    //   id: id
    // });
    // if (response.errorCode === 0) {
    //   this.formData = response.data;
    // }

  },
  data: function () {

    const validateSettlementType = (rule, value, callback) => {
      if (!value || value === 0 || value === '0') {
        callback(new Error('请选择结算类型'));
      } else {
        callback();
      }
    };
    const validateDaterange = (rule, value, callback) => {
      if (Array.isArray(value)) {
        if (!value[0] || !value[1]) {
          callback(new Error('日期不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateRevenueType = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择收入确认类型'));
      } else {
        if (value === 'FIXED_SCALE' && !this.formData.platformRevenueCcale) {
          callback(new Error('请输入平台应收比例'));
        } else if (value === 'FIXED_AMOUNT' && !this.formData.platformRevenueAmount) {
          callback(new Error('请输入平台应收金额'));
        } else {
          callback();
        }

      }
    };

    return {
      maxlength: 32,
      taxpayerId: this.$route.params.id,
      formRef: Uuid.v1(),
      formData: {
        beginTime: [],
        channelList: [],
        platformRevenueAmount: 0,//平台应收金额
        platformRevenueCcale: 0,//平台应收比例
      },
      columns: [],
      ditchTitle: [],
      selectChannel: [], // 渠道选择
      selectScenario: [], // 场景选择
      settlementTypes: [{key: '1', value: '清分'}, {key: '2', value: '自营'}, {key: '3', value: '平台'}],//结算类型
      oNameSelect: [], // 机构名称
      selectRevenueTypeList: [], // 收入确认规则选择
      selectAccount: [], // 结算账户类型
      cityList: [],
      ruleFormData: {
        organizationCode: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        merchantName: [{
          required: true,
          message: '请填写',
          trigger: 'blur'
        }],
        // openingBank: [{
        //   required: true,
        //   message: '请填写',
        //   trigger: 'blur'
        // }],
        // accountName: [{
        //   required: true,
        //   message: '请填写',
        //   trigger: 'blur'
        // }],
        // bankCode: [{
        //   required: true,
        //   message: '请填写',
        //   trigger: 'blur'
        // }],
        accountType: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        // accountNo: [{
        //   required: true,
        //   message: '请填写',
        //   trigger: 'blur'
        // }],
        channelListType: [{
          required: true,
          type: 'array',
          message: '请选择',
          trigger: 'change'
        }],
        settlementType: [{
          required: true,
          validator: validateSettlementType,
          trigger: 'change'
        }],
        // scene: [{ required: true, type: 'array', message: '请选择', trigger: 'change' }],
        beginTime: [{
          required: true,
          validator: validateDaterange,
          trigger: 'change'
        }],
        revenueType: [{
          required: true,
          validator: validateRevenueType,
          trigger: 'change'
        }]
        // city: [{
        //   required: true,
        //   type: 'array',
        //   message: '请选择',
        //   trigger: 'change'
        // }]
      }
    };
  },
  created() {
    this.getInstitutionName();
    this.getSelectKey();
    this.getCity();
    this.getChannelList();
    /** 渠道 */
    this.getRevenueType()
  },
  methods: {
    trim(value) {
      return value.trim();
    },
    /** 整整数验证 **/
    validateTageCount(rule, value, callback) {
      let tag = /^[0-9a-zA-Z]{1,32}$/;
      // ^[A-Za-z0-9]+$
      if (value === '') {
        callback(new Error('请正确填写商户号'));
      } else if (!tag.test(this.formData.channelList[rule.index].subMchId)) {
        callback(new Error('请正确填写商户号'));
      } else {
        callback();
      }
    },

    /** 商户百分比验证 */
    validateTage(rule, value, callback) {
      let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/;
      if (value === '') {
        callback(new Error('请输入数字'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字且保留两位小数'));
      } else if (value > 100 - this.formData.channelList[rule.index].platformSlottingFees) {
        callback(new Error('平台应收和商户平台之和不能超过100%'));
      }
      callback();
    },

    /** 平台百分比验证 */
    validateTageCheak(rule, value, callback) {
      let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/;
      if (!value) {
        callback(new Error('请输入数字'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字且保留两位小数'));
      } else if (value > 100 - this.formData.channelList[rule.index].merchantSlottingFees) {
        callback(new Error('平台应收和商户平台之和不能超过100%'));
      } else {
        callback();
      }
    },

    getCityName(item, selectedData) {
      if (selectedData.length > 1) {
        this.formData.cityCode = selectedData[1].value;
        this.formData.cityName = selectedData[1].label;
        this.formData.provinceCode = selectedData[0].value;
        this.formData.provinceName = selectedData[0].label;
      } else if (selectedData.length > 0) {
        this.formData.cityCode = selectedData[0].value;
        this.formData.cityName = selectedData[0].label;
        this.formData.provinceCode = '';
        this.formData.provinceName = '';
      } else {
        this.formData.cityName = '';
        this.formData.cityCode = '';
      }
    },
    /** 获取地级市 */
    async cityLoadData(item, callback) {
      try {
        let id = {
          pid: item.value
        };
        item.loading = true;
        let res = await this.$store.dispatch(
          `${namespace}/getCityData`,
          id
        );
        if (res.data.ret === 0) {
          item.children = res.data.data.map(
            ({name, pid, adcode, id}) => {
              return {
                label: name,
                value: id
              };
            }
          );
          item.loading = false;
          callback();
        }
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    // 城市
    async getCity() {
      try {
        let params = {
          pid: 1
        };
        let res = await this.$store.dispatch(`${namespace}/getCityData`, params);
        this.cityList = res.data.data.map(({name, pid, adcode, id}) => {
          if (['北京', '天津', '上海', '重庆', '澳门', '香港'].includes(name)) {
            return {
              label: name,
              value: id
            };
          } else {
            return {
              label: name,
              value: id,
              children: [],
              loading: false
            };
          }
        });
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    async getRevenueType() {
      try {
        let res = await this.$store.dispatch(`${namespace}/revenueTypeList`, {});
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.selectRevenueTypeList = data.map(({revenueType, revenueTypeName}) => {
            return {
              value: revenueType,
              label: revenueTypeName
            };
          });
        }
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    // 组织机构下拉
    getInstitutionName() {
      this.$store.dispatch(`${namespace}/getInstitutionName`).then((res) => {
        if (res.data.errorCode === 0) {
          let data = res.data.data.list.map(({organizationCode, organizationName}) => {
            return {
              label: organizationName,
              value: organizationCode
            };
          });
          this.oNameSelect = data;
        }
      });
    },
    // 字典
    getSelectKey() {
      this.$store.dispatch(`${namespace}/getMerchantSearchKey`).then((res) => {
        if (res.data.errorCode === 0) {
          let data = res.data.data;
          console.log(data, '字典');
          // this.selectChannel = data.merchantPaymentChannel; // 渠道
          this.selectAccount = data.merchantAccountType; // 结算类型
          this.selectScenario = data.merchantScenario; // 业务场景
        }
      });
    },
    blandleOrganization(val) {
      this.formData.organizationName = val ? val.label : '';
    },
    setDateRange(value) {
      this.formData.beginTime = value;
      this.formData.contractStartDate = value[0];
      this.formData.contractEndDate = value[1];
    },
    goBack() {
      this.$router.go(-1);
    },
    getDitch(val) {
      this.formData.channelList = [];
      if (val.length === 0) this.ditchTitle = [];
      for (var i = 0; i < val.length; i++) {
        this.ditchTitle = val;
        let obj = {
          paymentChannelName: val[i].label,
          paymentChannelCode: val[i].value, // 渠道标识
          merchantSlottingFees: '',
          subMchId: '',
          platformSlottingFees: '',
          merchantCodeBusiness: '',
          merchantCodeAcquirer: '',
          subAppid: '',
          enterpriseCode: '',
          used:'0'
        };
        this.formData.channelList.push(obj);
      }
    },

    /** 获取渠道 */
    async getChannelList() {
      try {
        let params = {
          currentPage: 1,
          pageSize: 9999
        };
        let res = await this.$store.dispatch(`${namespace}/channelList`, params);
        if (res.data.ret === 0) {
          let data = res.data.data.list;
          this.selectChannel = data.map(({paymentChannelCode, paymentChannelName}) => {
            return {
              key: paymentChannelCode,
              value: paymentChannelName
            };
          });
        }
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },

    handleSubmit(name) {
      try{
        this.$refs[name].validate(valid => {
          if (valid) {
            if (this.formData.revenueType === 'FIXED_SCALE') {
              this.formData.platformRevenueAmount = 0
            } else if (this.formData.revenueType === 'FIXED_AMOUNT') {
              this.formData.platformRevenueCcale = 0
            } else {
              this.formData.platformRevenueAmount = 0
              this.formData.platformRevenueCcale = 0
            }
            if (this.formData.channelList && this.formData.channelList.length > 0) {
              const usedChannels = this.formData.channelList.filter(item => item.used && (item.used === '1'||item.used === 1))
              if (usedChannels.length > 1) {
                this.$Message.error("一个商户只能设置一个渠道生效！")
                return false;
              }
              if(usedChannels.length===0){
                Modal.confirm({
                  title: "未配置商户默认支付渠道",
                  content: "将导致商户无法下单交易，确定提交吗？？？",
                  okText: "去配置",
                  cancelText: "确定提交",
                  onOk: async () => {
                    this.$Message.info("请设置商户默认渠道！")
                  },
                  onCancel: async ()=>{
                    await this.submitData()
                  }
                });
              }else{
                this.submitData()
              }
            }else{
              this.submitData()
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }catch (err) {
        console.log(err)
      }
    },
    async submitData(){
      if (undefined !== this.formData.scene) {
        this.formData.scene = this.formData.scene.join(',');
      }
      this.$store.dispatch(`${namespace}/save`, this.formData).then(res => {
        if (res.errorCode === 0) {
          this.$Message.success(res.msg);
          this.$router.push('commercial');
          this.$store.dispatch(`${namespace}/query`);
        } else {
          this.$Message.warning(res.msg);
        }
      });
    },
    handleSubmitCancel(name) {
      this.$router.push('commercial');
      this.$refs[name].resetFields();
    },
  },
  computed: {
    loading: function () {
      let result = this.$store.state[namespace].loading;
      return result;
    }
  }
};
</script>

<style lang="less">
.ditchBox {
  .ditchTitle {
    margin-bottom: 20px;
  }

  .ivu-date-picker {
    width: 100%
  }
}

.pageWrapperForm {
  .ivu-form {
    .ivu-form-item-label {
      padding-right: 2px;
      font-weight: bold;
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    }
  }

  .ivu-card {
    margin-bottom: 5px;
  }

  .ivu-form-item-content {
    display: flex;
    display: -webkit-flex;
  }


  .ivu-date-picker {
    width: 100%;
  }

  .ivu-form-inline .ivu-form-item {
    width: 90%;
  }


  .ivu-input,
  .ivu-select {
    min-width: 120px;
  }

  .ivu-form-item {
    margin-bottom: 20px;
  }

  th .ivu-table-cell {
    display: inline-block;
    word-wrap: normal;
    vertical-align: middle;
    font-size: 12px;
  }

}
</style>


